<template>
  <div class="plan-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>套餐列表</span>
          <el-button type="primary" @click="handleAddPlan">添加套餐</el-button>
        </div>
      </template>

      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="套餐名称">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入套餐名称"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="loading" :data="planList" row-key="id">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="套餐名称" width="120" />
        <el-table-column prop="amount" label="价格" width="100">
          <template #default="scope"> ¥{{ scope.row.amount }} </template>
        </el-table-column>
        <el-table-column prop="amount" label="原价" width="100">
          <template #default="scope">
            <span v-if="scope.row.origin_price">¥{{ scope.row.amount }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="套餐描述"
          show-overflow-tooltip
        />
        <el-table-column prop="sort" label="排序" width="80" />
        <!-- <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <!-- <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? "禁用" : "启用" }}
            </el-button> -->
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getPlanList, updatePlanStatus, deletePlan } from "@/api/plans";

const router = useRouter();
const loading = ref(false);
const planList = ref([]);
const total = ref(0);

const queryParams = reactive({
  page: 1,
  limit: 10,
  name: "",
  type: "",
  status: "",
});

// 获取套餐列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getPlanList(queryParams);
    if (res.code === 0) {
      planList.value = res.data.items;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || "获取套餐列表失败");
    }
  } catch (error) {
    console.error("获取套餐列表失败", error);
    ElMessage.error("获取套餐列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.name = "";
  queryParams.type = "";
  queryParams.status = "";
  handleQuery();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.limit = val;
  queryParams.page = 1;
  getList();
};

// 添加套餐
const handleAddPlan = () => {
  router.push("/plan/add");
};

// 编辑套餐
const handleEdit = (row) => {
  router.push(`/plan/edit/${row.id}`);
};

// 切换套餐状态
const handleStatusChange = (row) => {
  const statusText = row.status === 1 ? "禁用" : "启用";
  const newStatus = row.status === 1 ? 0 : 1;

  ElMessageBox.confirm(`确认要${statusText}该套餐吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updatePlanStatus(row.id, newStatus);
        if (res.code === 0) {
          ElMessage.success(`${statusText}成功`);
          getList();
        } else {
          ElMessage.error(res.message || `${statusText}失败`);
        }
      } catch (error) {
        console.error(`${statusText}失败`, error);
        ElMessage.error(`${statusText}失败`);
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 删除套餐
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认要删除套餐 "${row.name}" 吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deletePlan(row.id);
        if (res.code === 0) {
          ElMessage.success("删除成功");
          getList();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 获取套餐类型名称
const getPlanTypeName = (type) => {
  const typeMap = {
    month: "月套餐",
    quarter: "季套餐",
    year: "年套餐",
    permanent: "永久套餐",
  };
  return typeMap[type] || "未知";
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.plan-list-container {
  height: 100%;
  padding: 20px;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.el-table {
  flex: 1;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容样式优化 */
:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  line-height: 1.5;
}

/* 按钮样式调整 */
.card-header .el-button {
  padding: 9px 16px;
}

.el-table .el-button {
  padding: 6px 12px;
  margin: 0 4px;
}

.el-tag {
  font-weight: 500;
}
</style>
